package cn.aishua.util;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * This helper is used to send http request to web service
 * 
 * @author tonggton
 * 
 */
public class HttpRequestHelper
{

    private static final int REQUEST_TIMEOUT = 5*1000; //  5 seconds 
    private static final int SO_TIMEOUT = 5*1000; // 5 seconds
    
    public static String HTTP_REQ_PARAM_NAME_MOBILE_NUMBER = "mobileNumber";
    public static String HTTP_REQ_PARAM_NAME_PASSWORD = "password";
    
    private static HttpClient httpClient;

    public static  HttpClient getHttpClient()
    {
        if( httpClient == null )
        {
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout( httpParams, REQUEST_TIMEOUT );
            HttpConnectionParams.setSoTimeout( httpParams, SO_TIMEOUT );
            httpClient = new DefaultHttpClient( httpParams );
        }
        return httpClient;
    }
    
    /**
     * 
     * @param urlPost
     * @param params
     * @return response of this request
     */
    public static String sendPostRequest( String urlPost, List<NameValuePair> params )
    {

        String response = null;
        HttpPost req = new HttpPost( urlPost );
        HttpResponse res = null;
        try
        {
            req.setEntity( new UrlEncodedFormEntity( params, HTTP.UTF_8 ) );

            res = getHttpClient().execute( req );

            if( res.getStatusLine().getStatusCode() == 200 )
            { // succeed to connect
                response = EntityUtils.toString( res.getEntity() );
            }
            else
            {
                response = "连接失败";
            }
        }
        catch( Exception e )
        {
            e.printStackTrace();
            response = "连接失败";
        }
        return response;
    }

}
